package com.fzu.geometa.metadata.eventdriven.publisher;

import cn.hutool.core.util.ObjectUtil;
import com.fzu.geometa.metadata.eventdriven.event.MetadataAddEvent;
import com.fzu.geometa.metadata.eventdriven.event.MetadataDeleteEvent;
import com.fzu.geometa.metadata.eventdriven.event.MetadataUpdateEvent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationEvent;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class MetadataEventPublisher {
    @Autowired
    ApplicationContext applicationContext;

    @Value("${enable-search}")
    private boolean enableSearch;

    public void publish(ApplicationEvent event){
        // 是否开启了检索更新
        if (!enableSearch) {
            // 没有开启更新
            return;
        }

        if (ObjectUtil.isNull(event)) {
            return;
        }
        //发布事件
        applicationContext.publishEvent(event);
    }

    public void publishAddEvent(Long cid) {
        publish(new MetadataAddEvent(this, cid));
    }

    public void publishUpdateEvent(Long cid) {
        publish(new MetadataUpdateEvent(this, cid));
    }

    public void publishDeleteEvent(List<Long> deletedIds) {
        MetadataDeleteEvent metadataDeleteEvent = new MetadataDeleteEvent(this);
        for (Long deletedId : deletedIds) {
            metadataDeleteEvent.addId(deletedId);
        }
        publish(metadataDeleteEvent);
    }

    public void publishDeleteEvent(Long cid) {
        MetadataDeleteEvent metadataDeleteEvent = new MetadataDeleteEvent(this);
        metadataDeleteEvent.addId(cid);
        publish(metadataDeleteEvent);
    }

}
